#!/usr/bin/env python
# coding:utf-8

"""
Created by ben on 2010/10/26 .
Copyright (c) 2010 http://sa3.org All rights reserved. 
"""
import re
import logging
import random
import string
import os
import urllib, hashlib
import time,datetime
import math

from google.appengine.ext import db
from util.b36 import Base36
from util.base import filter_url, read_cookies
from util.thumb import resize
from google.appengine.api import images, memcache
from util.paging import PagedQuery
from util.rand import rand

PAGESIZE = 24 
PAGETIMES = 3
COMMENTSIZE = 10

def get_md5(bf):
    return hashlib.md5(bf).hexdigest()

def format_time(t):
    if isinstance(t, datetime.datetime):
        timestamp = time.mktime(t.timetuple())
        nowtime = time.time()
        timediff = nowtime - timestamp
        h = int(time.strftime("%H", time.localtime(nowtime))) * 3600
        if timediff > h:
            return t.strftime("%Y-%m-%d")
        else:
            return t.strftime("%I:%M %p")

def getVerificationCode(l=4):
    _code = rand(l, True, False, True, False)
    sessionId = read_cookies('FCD_SESSION_ID')
    sessionData = memcache.get('%s' % sessionId)
    bg = False
    if sessionData is not None:
        if sessionData.get('verification_code') is not None:
            verification_code = sessionData.get('verification_code')
            sessionData['verification_code']['code'] = _code
            sessionData['verification_code']['code_expires'] = time.time()
            if verification_code.get('bg') is not None:
                bg = True
        else:
            sessionData['verification_code'] = {'code': _code, 'code_expires': time.time()}

        memcache.set('%s' % sessionId, sessionData, 86400)

    if bg == True:
        imgBG = sessionData.get('verification_code').get('bg')
    else:
        imgBG = ImageSystem.all().filter('name =', 'bg.png').get()
        if sessionData is None:
            sessionData = {'verification_code': {'bg':imgBG}}
        else:
            if sessionData['verification_code'] is None:
                sessionData['verification_code'] = {'bg':imgBG}
            else:
                sessionData['verification_code']['bg'] = imgBG
        memcache.set('%s' % sessionId, sessionData, 86400)
    ileft = random.randint(0, imgBG.width-l*30)
    iwidth = ileft + l*30
    box = [float(ileft)/float(imgBG.width), 0.0, float(iwidth)/float(imgBG.width), 1.0]
    img = [[images.crop(imgBG.bf, box[0], box[1], box[2], box[3]), 0, 0, 1.0, images.TOP_LEFT]]

    fontimg = sessionData.get('verification_code').get('fimg')
    if fontimg is None:
        fonts = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        for i in range(0, len(fonts)):
            f = fonts[i:i+1]
            imgf = ImageSystem.all().filter('name =', '%s.png' %f).get()
            if imgf is not None:
                if sessionData['verification_code'].get('fimg') is None:
                    sessionData['verification_code']['fimg'] = {'%s' % f: imgf}
                else:
                    sessionData['verification_code']['fimg']['%s'% f] = imgf

        memcache.set('%s' % sessionId, sessionData, 86400)
    for i in range(0, l):
        f = _code[i:i+1]
        if sessionData['verification_code']['fimg'].get(f) is None:
            imgf = ImageSystem.all().filter('name =', '%s.png' % f).get()
            if imgf is not None:
                sessionData['verification_code']['fimg']['%s'% f] = imgf
        else:
            imgf = sessionData['verification_code']['fimg'].get(f)

        img.append([imgf.bf, int(i*30), 0, 1.0, images.TOP_LEFT])
    
    im = images.composite(img, l*30, 30, 0)

    return im

class Album(db.Model):
    '''
    sa3album Album Model
    '''
    slug = db.StringProperty()
    name = db.StringProperty()
    description = db.StringProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    last_updated = db.DateTimeProperty(auto_now=True)
    cover_url = db.StringProperty()

    def put(self):
        self.slug = self.key().name()
        super(Album,self).put()
    
    @property
    def url(self):
        return "/b/%s/" % (self.slug)
    
    @property
    def m_url(self):
        return "/a/album/manage/%s/" % (self.slug)
    
    @property
    def count(self):
        return Image.all().filter('album =',self).count()
    
    @classmethod
    def add(cls,name):
        album = Album(name = name,key_name = Counter.get_max('album'))
        album.put()
        return album

    @classmethod
    def get_album_list(cls, s):
        if s is None:
            s = 20

        album = memcache.get('album_list_side')
        if album is None:
            albs = Album.all().fetch(s)
            if albs is not None:
                album = []
                for a in albs:
                    album.append({'name':a.name, 'url': '/b/%s' % a.key().name()})

                memcache.set('album_list_side', album, 3600*24)
            
            else:
                album = None

        return album

    @classmethod
    def get_album(cls, ab_name):
        if ab_name is None:
            return None

        albs = Album.all().filter('name =', ab_name).get()
        if albs is None:
            albs = Album.add(ab_name)

        return albs
    
class Image(db.Model):
    '''
    sa3album Photo Model
    '''
    album = db.ReferenceProperty(Album)
    name = db.StringProperty()
    mime = db.StringProperty()
    size = db.IntegerProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    description = db.StringProperty()
    width = db.IntegerProperty()
    height =db.IntegerProperty()
    bf = db.BlobProperty()
    md5 = db.StringProperty(indexed=True)
    
    view_count = db.IntegerProperty(default=0) #view count
    like_count = db.IntegerProperty(default=0)
    comments_count = db.IntegerProperty(default=0)
    
    def put(self):
        if self.is_saved():
            memcache.delete("f::%s" % self.key().name())
        super(Image,self).put()
    
    def delete(self):
        memcache.delete("s::%s" % self.key().name())
        memcache.delete("f::%s" % self.key().name())
        super(Image,self).delete()
    
    @property
    def url(self):
        return "/d/%s/" %(self.key().name())
    
    @property
    def s(self):
        ''' small image url '''
        return "/s/%s/" %(self.key().name())
    
    @property
    def download_url(self):
        '''downlaod url'''
        return "/e/%s/" % (self.key().name())
    
    @property
    def f(self):
        return "/f/%s/" %(self.key().name())
    
    @property
    def copyurl(self):
        return "http://%s/f/%s/" %(os.environ['HTTP_HOST'],self.key().name())
    
    @property
    def next(self):
        '''return next image'''
        return Image.all().filter('album =',self.album).order('created').filter('created >', self.created).get()
    
    @property
    def prev(self):
        '''return  prev image'''
        return Image.all().filter('album =',self.album).order('-created').filter('created <', self.created).get()
    
    @property
    def body(self):
        if self.bf:
            return self.bf
        bfs = ImageBF.all().filter('image =',self)
        bf = bfs.order('vid').fetch(10)
        if not bf:
            bf = self.bfs
        return ''.join([f.bf for f in bf])
    
    @property
    def des(self):
        '''
        Return image description,default :imgage name
        '''
        return self.description if  self.description else self.name
    
    def get_resize_img(self,w,h):
        key = "r::%s::%s::%s" % (self.key().name(),w,h)
        data = memcache.get(key)
        if data is None:
            logging.info("generate thumb image key:%s" % key)
            data = resize(self.body,(w,h))
            #make true data size < 1000000
            if len(data) < 1000000:
                memcache.set(key,data,3600*24)
        return data
        
    @classmethod
    def add(cls,album,name,mime,bf,**kwargs):
        #先检查md5看图片是否已经上传过.
        md5 = get_md5(bf)
        img = Image.all().filter('md5 =',md5).get()
        if img and Setting.get_s().is_check_md5:
            logging.info("%s exist" % md5)
            return img
        
        key_name = Counter.get_max('image')
        size = len(bf)
        start =0
        splitelen=1000*1000 # 1M limit  
        if size <= splitelen:
            img = Image(album=album,name=name,mime=mime,bf=bf,key_name = key_name,size=size,**kwargs)
        else:
            img = Image(album=album,name=name,mime=mime,key_name = key_name,size=size,**kwargs)
            while start<img.size:
                ibf = ImageBF(bf=bf[start:start+splitelen],image = img,vid = start)
                ibf.put()
                start+=splitelen
            
        t = images.Image(image_data=bf)
        img.width = t.width
        img.height = t.height
        img.md5 = get_md5(bf)
        img.put()
        return img

    @classmethod
    def updateCommentCount(cls, key_name, c):
        if key_name is None:
            return False
        
        if c is None:
            return False

        img = Image.get_by_key_name(key_name)
        if img is None:
            return False
        else:
            img.comments_count += c
            img.put()
            return True

    @classmethod
    def updateLike(cls, key_name, session_id):
        ls = memcache.get(session_id)
        if ls is None:
            updateFlag = True
        else:
            lss = ls.get('uplike')
            if lss is None:
                updateFlag = True
            else:
                lsk = lss.get('key_%s' % key_name)
                if lsk is None:
                    updateFlag = True
                else:
                    return '["E_LIKED", 0]'

        if updateFlag == True:
            img = Image.get_by_key_name(key_name)
            if img is None:
                return '["E_IMG_NOT_EXISTS", 0]'
            else:
                img.like_count = img.like_count + 1
                img.put()
                if ls is None:
                    ls = {'uplike': {'key_%s' % key_name: img.like_count}}
                else:
                    if ls.get('uplike') is None:
                        ls['uplike'] = {'key_%s' % key_name: img.like_count}
                    else:
                        ls['uplike']['key_%s' % key_name] = img.like_count
                memcache.set(session_id, ls, 86400)
                return '["E_UPDATE_SUCCESSED", %s]' % img.like_count
    
    @classmethod
    def get_by_key_name_with_cache(cls,key_name):
        key = "f::%s" % key_name
        data = memcache.get(key)
        if data is None:
            data =Image.get_by_key_name(key_name)
            memcache.set(key,data,3600*24)
        return data

    @classmethod
    def get_img_list(cls, p, i, f):
        if f is None:
            imgkey = "il-img::%s::%s" % (p, i)
        else:
            imgkey = "il-img::%s::%s::%s" % (p, i, f.key().name())

        ckey = "il-comments::%s::%s" % (p, i)
        imgStr = memcache.get(imgkey)
        if imgStr is None:
            if f is None:
                imgs = PagedQuery(Image.all().order('-created'), PAGESIZE)
            else:
                imgs = PagedQuery(Image.all().filter('album =', f).order('-created'), PAGESIZE)

            temp = imgs.fetch_page(((p-1)*PAGETIMES+i))
            imgStr = '"i":[';
            cStr = '"c":{';
            imgArr = []
            for img in temp:
                cStr += '"%s": %s,' % (img.key().name(), Comments.get_comments(img.key().name(), None))
                imgStr += '{"k": "%s", "s": "%s", "n": "%s", "w":%s, "h":%s, "vc": %s, "lc": %s},' % (img.key().name(), img.f, img.name, img.width, img.height, img.view_count, img.like_count)
                imgArr.append(img.key().name())

            if len(imgStr) > 5:
                imgStr = imgStr[:-1] + ']'
                cStr = cStr[:-1] + '}'
                memcache.set(imgkey, imgStr, 3600*24)
                memcache.set("il-img-arr::%s::%s" %(p, i), imgArr, 3600*24)
                memcache.set(ckey, cStr, 3600)
                showStr = '{%s,%s}' % (imgStr, cStr)
            else:
                showStr = '{"i":[], "c":{}}'
        else:
            cStr = memcache.get(ckey)
            if cStr is None:
                cStr = '"c":{';
                imgs = memcache.get("il-img-arr::%s::%s" %(p, i))
                for img in imgs:
                     cStr += '"%s": %s,' % (img, Comments.get_comments(img, None))
                
                if len(cStr) > 5:
                    cStr = cStr[:-1] + '}'
                else:
                    cStr += '}'

                showStr = '{%s,%s}' % (imgStr, cStr)
            else:
                showStr = '{%s,%s}' % (imgStr, cStr)
        
        return showStr
    
    @classmethod
    def get_small_img(cls, t, n, f):
        if n is None:
             n = 9

        if t is None:
             t = ['newimg', '-created']
        
        if f is None:
            key = "%s" % t[0]
        else:
            key = "%s::%s_%s" % (t[0], f[0], f[1])

        _img = memcache.get(key)
        if _img is None:
            if f is None:
                imgs = Image.all().order('%s' % t[1]).fetch(n)
            else:
                imgs = Image.all().filter('%s =' % f[0], f[1]).order('%s' % t[1]).fetch(n)

            i=0
            iStr=''
            for img in imgs:
                memcache.set("%s%s" % (key, i) , img, 3600*24)
                iStr += "%s%s|" % (key, i)
                i+=1

            if len(iStr) > 0:
                iStr = iStr[:-1]
                _img = memcache.set("%s" % key, iStr, 3600*24)
        
        else:
            imgs = []
            newimgArr = _img.split('|')
            for imgi in newimgArr:
                img = memcache.get(imgi)
                if img is not None:
                    imgs.append(img)

        return imgs

    @classmethod
    def get_img_count(cls, f, o):
        key = "img_count"
        if f is not None:
            key += "::f_%s" % f[1].key().name()
        
        if o is not None:
            key += "::o_%s" % o[1]
        
        tp = memcache.get(key)
        if tp is None:
            imgo = Image.all()
            if f is not None:
                imgo = imgo.filter("%s =" %f[0], f[1])

            if o is not None:
                imgo = imgo.order("%s" %o[1])

            imgs = PagedQuery(imgo, PAGESIZE * PAGETIMES)
            tp = imgs.page_count()
            memcache.set(key, tp)
        
        return tp

            
class Comments(db.Model):
        img_key = db.StringProperty()
        user_key = db.StringProperty()
        comments = db.StringProperty()
        created = db.DateTimeProperty(auto_now_add=True)

        def put(self, ik):
            if self.is_saved():
                memcache.delete("c::%s" % ik)
            super(Comments,self).put()

        @classmethod
        def add(cls, user_name, user_email, user_url, _comments, ikey, vercode):
            sessionId = read_cookies('FCD_SESSION_ID')
            sessionData = memcache.get('%s' % sessionId)
            nows = time.time() - sessionData['verification_code']['code_expires']
            if nows > 60:
                return '{"status":false, "msg": "VERCODE_NOT_EQ"}'

            if vercode.upper() == sessionData['verification_code']['code']:
                cm = Comments(user_key = Users.get_by_user_key(user_name,user_email,user_url), img_key = ikey, comments = _comments, key_name = Counter.get_max('comments'))
                cm.put(ikey)
                Image.updateCommentCount(ikey, 1)
                return '{"status":true, "msg": "ADD_COMMENT_SUCCESSED"}'
            else:
                return '{"status":false, "msg": "VERCODE_NOT_EQ"}'
        

        @classmethod
        def get_by_key_with_cache(cls, ikey):
            key = "c::%s" % ikey
            data = memcache.get(key)
            if data is None:
                data = Comments.get_by_img_key(ikey)
                memcache.set(key,data,3600*24)
            return data
         
        @classmethod
        def get_by_img_key(cls, ikey):
            cm = Comments.all().filter('user_key =', ikey).get()
            if cm:
                return cm
        
        @classmethod
        def get_comments(self, key_name, p):
            tp = 0
            if p is None:
                cms = Comments.all().filter('img_key =', key_name).order('-created').fetch(2)
            else:
                if p < 1 or p is None:
                    p = 1
                
                cmsp = PagedQuery(Comments.all().filter('img_key =', key_name).order('-created'), COMMENTSIZE)
                cms = cmsp.fetch_page(int(p))

                cmsn = Comments.all().filter('img_key =', key_name).count()
                tp = int(math.ceil(cmsn/float(COMMENTSIZE)))
                if p > tp:
                    p = tp

                if cmsn < 1:
                    return '{"n":0, "tp": %s}' %tp

            if cms:
                s = '{"d": ['
                i = 0
                for cm in cms:
                    us = Users.get_by_key_name(cm.user_key)
                    s += '{"un": "%s", "av": "%s", "ct": "%s", "ur": "%s", "tt": "%s"},' % (us.name, Users.get_gravtar_url(us.email, 25), cm.comments, us.url, format_time(cm.created))
                    i += 1
                
                if i > 0:
                    s = s[:-1] + '], "n": %s, "tp":%s}' % (i,tp)
                else:
                    s += '], "n": 0, "tp": 0}'

                return s

            else:
                return '{"n":0, "tp": 0}'
        

class Users(db.Model):
        name = db.StringProperty()
        email = db.StringProperty()
        url = db.StringProperty()
        created = db.DateTimeProperty(auto_now_add=True)

        def put(self):
            super(Users,self).put()

        @property
        def f(self):
            return "/u/%s/" %(self.key().name())

        @classmethod
        def get_by_user_key(cls, user_name,user_email,user_url):
            us = Users.all().filter('email =', user_email).get()
            if us:
                return us.key().name()

            us = Users(name = user_name, email = user_email, url = user_url, key_name = Counter.get_max('users'))
            us.put()

            return us.key().name()

        @classmethod
        def get_gravtar_url(cls, user_email, asize):
            default = '1e78eecfe72005087617f5f4060e72ae?s=25&r=G' #http://www.gravatar.com/avatar/
            if not user_email:
                return default

            if not asize:
                size = 25
            else:
                size = asize
            # construct the url
            imgurl = ""
            imgurl += hashlib.md5(user_email).hexdigest()+"?"+ urllib.urlencode({'s':str(size),'r':'G'}) #'d':default,
            return imgurl

class ImageBF(db.Model):
    '''Image binary file'''
    bf = db.BlobProperty()
    image = db.ReferenceProperty(Image,collection_name='bfs')
    vid = db.IntegerProperty(default=0)

class ImageSystem(db.Model):
    '''Image binary file'''
    bf = db.BlobProperty()
    name = db.StringProperty()
    created = db.DateTimeProperty(auto_now_add =True)
    width = db.IntegerProperty(default=0)
    height = db.IntegerProperty(default=0)
    size = db.IntegerProperty(default=0)
    mime = db.StringProperty()
    md5 = db.StringProperty(indexed=True)

    @classmethod
    def add(cls,name,mime,bf,**kwargs):
        #先检查md5看图片是否已经上传过.
        md5 = get_md5(bf)
        img = ImageSystem.all().filter('md5 =',md5).get()
        if img and Setting.get_s().is_check_md5:
            logging.info("%s exist" % md5)
            return img
        
        size = len(bf)
        start =0
        splitelen=1000*1000 # 1M limit  
        if size <= splitelen:
            img = ImageSystem(name=name,mime=mime,bf=bf,size=size,**kwargs)
        else:
            img = ImageSystem(name=name,mime=mime,size=size,**kwargs)
            while start<img.size:
                ibf = ImageBF(bf=bf[start:start+splitelen],image = img,vid = start)
                ibf.put()
                start+=splitelen
            
        t = images.Image(image_data=bf)
        img.width = t.width
        img.height = t.height
        img.md5 = get_md5(bf)
        img.put()
        return img
    
class Counter(db.Model):
    '''
    sa3album Counter Model
    '''
    name = db.StringProperty(required=False)
    value = db.StringProperty(default ='0') #use base36
    created = db.DateTimeProperty(auto_now_add =True)
    last_updated = db.DateTimeProperty(auto_now = True)
    
    def put(self):
        self.name = self.key().name()
        super(Counter,self).put()
        
    @classmethod
    def get_count(cls,key_name):
        obj = Counter.get_by_key_name(key_name)
        if obj is None:
            obj = Counter(key_name = key_name)
            obj.value = '0'
            obj.put()
        return obj
    
    @classmethod
    def get_max(cls,key_name):
        '''
        return max value +1
        '''
        obj = Counter.get_count(key_name)
        obj.value = Base36(obj.value)+1
        obj.put()
        return obj.value
    
class Setting(db.Model):
    name = db.StringProperty()
    theme = db.StringProperty()
    skey = db.StringProperty()
    is_anti_leech = db.BooleanProperty(default=False)
    allow_list = db.StringListProperty()
    anti_leech_img = db.StringProperty()
    copy_txt = db.StringProperty()
    api_keys = db.StringListProperty()
    
    #twitter settings
    user_key = db.StringProperty()
    user_secret = db.StringProperty()
    twitter_user = db.StringProperty()
    twitter_auto = db.BooleanProperty(default=False)

    is_check_md5 = db.BooleanProperty(default=False)
    image_thumb_width = db.IntegerProperty(default=200)
    image_thumb_height = db.IntegerProperty(default=0)
    pic_total_number = db.IntegerProperty(default=0)
    
    version = '0.2.6'
    path = "http://%s" % os.environ['HTTP_HOST']
    
    @classmethod
    def get_s(cls):
        s = Setting.get_by_key_name('s')
        if s is None:
            skey = ''.join(random.sample(string.ascii_letters,16))
            s = Setting(key_name = 's',name ='sa3album',theme='gallery',skey=skey)
            s.put()
            #add default album
            Album.add('default')
        return s
    
    @classmethod
    def flush_total_pic_num(cls, n):
        s = Setting.get_by_key_name('s')
        if s is None:
            self.get_s()
        else:
            s.pic_total_number = n
            s.put()
        return s

    @classmethod
    def get_total_pic_num(cls):
        s = Setting.get_by_key_name('s')
        n = 0
        if s is None:
            self.get_s()
        else:
            n = s.pic_total_number

        return n


class Pick(db.Model):
    name = db.StringProperty()
    base_url = db.StringProperty()
    method = db.IntegerProperty()
    method_time = db.StringProperty()
    ablum = db.StringProperty()
    page_method = db.IntegerProperty()
    page_url = db.StringListProperty()
    #rule = db.StringListProperty()
    #save_rule = db.StringListProperty()
    created = db.DateTimeProperty(auto_now_add =True)
      
    @classmethod
    def add(cls, pick_data):
        keyname = Counter.get_max('pick')
        pc = Pick(name=pick_data['name'], key_name=keyname);
        pc.base_url = pick_data['base_url']
        pc.method = pick_data['method']
        if pick_data.get('method_time'):
            pc.method_time = pick_data['method_time']
        pc.ablum = pick_data['ablum']
        pc.page_method = pick_data['page_method']
        """if len(pick_data['page_url']) > 0:
            for purl in pick_data['page_url']:"""
        pc.page_url = pick_data['page_url']
        if len(pick_data['rule_name']) > 0:
            i = 0
            for rulen in pick_data['rule_name']:
                if i == 0:
                    s = '%Base%'
                else:
                    s = pick_data['source_name'][i-1]
                
                rule = Pick_Rule(name=rulen, sources=s, data=pick_data['rule_contents'][i], pick_key_name=keyname, key_name=Counter.get_max('pick_rule'))
                rule.put();
                i+=1

        '''if len(pick_data['save_rule_name']) > 0:
            i = 0
            for saver in pick_data['save_rule_name']:
                pick_save = Pick_Save_Rule(name = saver, db=pick_data['save_data_name'][i], pick_key_name=keyname, key_name=Counter.get_max('pick_save_rule'))
                pick_save.put()
                i+=1'''
        pc.put()

        return True

    @classmethod
    def update(cls, pick_data, key_name):
        pc = Pick.get_by_key_name(key_name)
        pc.name = pick_data['name']
        pc.base_url = pick_data['base_url']
        pc.method = pick_data['method']
        if pick_data.get('method_time'):
            pc.method_time = pick_data['method_time']
        pc.ablum = pick_data['ablum']
        pc.page_method = pick_data['page_method']

        pc.page_url = pick_data['page_url']
        '''删除旧rule'''
        ruleo = Pick_Rule.all().filter('pick_key_name =', key_name)
        rulen = ruleo.count()
        rules = ruleo.fetch(rulen)
        if rules:
            for rule in rules:
                rule.delete()

        if len(pick_data['rule_name']) > 0:
            i = 0
            for rulen in pick_data['rule_name']:
                if i == 0:
                    s = '%Base%'
                else:
                    s = pick_data['source_name'][i-1]
                
                rule = Pick_Rule(name=rulen, sources=s, data=pick_data['rule_contents'][i], pick_key_name=key_name, key_name=Counter.get_max('pick_rule'))
                rule.put();
                i=i+1
        pc.put()

        return True

    @classmethod
    def deleteRule(self, key_name):
        picko = Pick.get_by_key_name(key_name)
        if picko:
            picko.delete()
        ruleo = Pick_Rule.all().filter('pick_key_name =', key_name)
        rulen = ruleo.count()
        rules = ruleo.fetch(rulen)
        if rules:
            for rule in rules:
                rule.delete()

        return True

    @classmethod
    def get_base(self, key_name):
        picko = Pick.get_by_key_name(key_name)
        if picko:
            return picko
        else:
            return False

    @classmethod
    def get_rule(self, key_name):
        ruleo = Pick_Rule.all().filter('pick_key_name =', key_name).order('created')
        rulen = ruleo.count()
        rules = ruleo.fetch(rulen)
        if rules:
            return rules
        else:
            return False


class Pick_Rule(db.Model):
    pick_key_name = db.StringProperty()
    name = db.StringProperty()
    sources = db.StringProperty()
    data = db.TextProperty()
    created = db.DateTimeProperty(auto_now_add =True)

'''class Pick_Save_Rule(db.Model):
    pick_key_name = db.StringProperty()
    name = db.StringProperty()
    db = db.StringProperty()'''


if __name__=='__main__':
    pass